var express = require('express');
var router = express.Router();
var db = require("../mysql/index.js");
/* GET users listing. */
router.get('/', function (req, res, next) {
  var sql = "SELECT id,lastname,firstname,login FROM users where type='User'";
  var webdata = {
    errCode: 0,
    errmsg: "",
    total: 0,
    pageSize: 0,
    pageNum: 0,
    data: []
  }
  db.query(sql).then(data1 => {
    var size = data1.data.length;
    webdata.total = size
    webdata.pageSize = size;
    webdata.pageNum = 0;
    webdata.data = data1.data;
    res.send(webdata)
  }).catch(err => {
    console.log(err)
    res.send({
      errCode: -1,
      errmsg: err.errmsg
    })
  })
});


router.get('/getUsersByGroupid', function (req, res, next) {
  var sql = `SELECT newusers.id,users.lastname FROM (SELECT group_users.group_id,users.*FROM group_users LEFT JOIN users ON group_users.user_id=users.id) AS newusers LEFT JOIN users ON newusers.group_id=users.id WHERE group_id=${req.query.id}`;
  var webdata = {
    errCode: 0,
    errmsg: "",
    total: 0,
    pageSize: 0,
    pageNum: 0,
    data: []
  }
  db.query(sql).then(data1 => {
    data1 = data1.data;
    var size = data1.length;
    webdata.total = size
    webdata.pageSize = size;
    webdata.pageNum = 0;
    webdata.data = data1.map(item => { delete item.consented_at; return item })
    res.send(webdata)
  }).catch(err => {
    console.log(err)
    res.send({
      errCode: -1,
      errmsg: err.errmsg
    })
  })
});

router.get('/groups', function (req, res, next) {
  var sql = `SELECT id,lastname FROM users WHERE type='Group'`;
  var webdata = {
    errCode: 0,
    errmsg: "",
    total: 0,
    pageSize: 0,
    pageNum: 0,
    data: []
  }
  db.query(sql).then(data1 => {
    data1 = data1.data;
    var size = data1.length;
    webdata.total = size
    webdata.pageSize = size;
    webdata.pageNum = 0;
    webdata.data = data1
    res.send(webdata)
  }).catch(err => {
    console.log(err)
    res.send({
      errCode: -1,
      errmsg: err.errmsg
    })
  })
});



module.exports = router;